package triangle.freshmanemail;

import java.util.ArrayList;

import triangle.utils.FastLoadFile;
import triangle.utils.ProgramWrapper;
import triangle.utils.SaveLoad;

public class EmailAddressSearcher {

//	 http://illinois.edu/ds/search?skinId=0&search=<firstname>+<middle name initial>+<last name>&search_type=all"
	private static String cacheFile = "cache.html";
	private static final String DISPLAYILLINOIS = "displayIllinois"; // key we are looking for
	private static final String DOMAINNAME = "@illinois.edu"; // illinois email addr domain name
	private static final int MAXNETIDLEN = 50; // netids can never be this long and I'm too lazy to fix this
	private static final int NETIDIDX = 1; // lazy hack...
	
	public static void main(String [] args)
	{
		EmailStoreStructure ess = new EmailStoreStructure("Matthew", "Frank", "N");
		obtainUrl(ess);
		System.out.println("Email address of nevada : " + ess.getEmailAddress());
	}
	
	public static void populateUrls(ArrayList<EmailStoreStructure> ess)
	{
		for (EmailStoreStructure es : ess)
		{
			obtainUrl(es);
			System.out.println(es);
		}
		
	}
	/**
	 * Assumes the last instance of address that shows up is the newbie.
	 * @param ess
	 * @return
	 */
	public static void obtainUrl(EmailStoreStructure ess)
	{
		ProgramWrapper.runProgram("wget -O " + cacheFile + 
				" http://illinois.edu/ds/search?skinId=0&search=" + ess.getWgetFormatName() + "&search_type=student");
		String displayIllinois = getAllDisplayIllinois();
		ess.setEmailAddress(displayIllinois);
	}
	
	/**
	 * 
	 * @return
	 */
	private static String getAllDisplayIllinois() 
	{

		String openedFile = FastLoadFile.loadFile(cacheFile);
		int lastIdx = openedFile.lastIndexOf(DISPLAYILLINOIS);
		if (lastIdx < 0) return "";
		String netIdContainString = openedFile.substring(lastIdx, lastIdx + MAXNETIDLEN);
		String [] netId = netIdContainString.split("\"");
		if (netId.length > 1) return netId[NETIDIDX] + DOMAINNAME;
		return "";
	}
}
